import { size, IFormProps, pageSize, dateTimeFormat } from "../../utils/common";
import React from "react";
import { connect } from "dva";
import {
  Form,
  Row,
  Col,
  Button,
  Input,
  Table,
  Popconfirm,
  Select,
  message
} from "antd";
import { PaginationProps } from "antd/lib/pagination";
import moment from "moment";
const Styles = require("../../styles/index.less");
import * as api from "../../api/api";
import Enumerable from "linq";

export interface IItemsPros extends IFormProps {
  item: any;
}
class Items extends React.PureComponent<IItemsPros, any> {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.getStores();
  }

  search = () => {
    this.getItems({ pageIndex: 1 });
  };

  getItemCategories = (payload?) => {
    payload = Object.assign({}, this.props.form.getFieldsValue(), {
      ...payload
    });
    this.props.dispatch({
      type: "item/getItemCategories",
      payload
    });
  };

  getRecommendCategories = (payload?) => {
    payload = Object.assign({}, this.props.form.getFieldsValue(), {
      ...payload
    });
    this.props.dispatch({
      type: "item/getRecommendCategories",
      payload
    });
  };

  getItems = (payload?) => {
    payload = Object.assign(
      {},
      this.props.item.itemSearchs,
      this.props.form.getFieldsValue(),
      { ...payload }
    );
    this.props.dispatch({
      type: "item/getItems",
      payload
    });
  };

  moveUp = id => {
    this.props.dispatch({
      type: "item/moveUpItem",
      payload: {
        form: { id },
        callback: () => {
          this.getItems();
        }
      }
    });
  };

  moveDown = id => {
    this.props.dispatch({
      type: "item/moveDownItem",
      payload: {
        form: { id },
        callback: () => {
          this.getItems();
        }
      }
    });
  };

  getStores = () => {
    this.props.dispatch({
      type: "item/getStores",
      payload: {
        callback: () => {
          this.getItemCategories();
          this.getRecommendCategories();
          this.getItems();
        }
      }
    });
  };

  reset = () => {
    this.props.form.resetFields();
  };

  add = () => {
    this.edit();
  };

  edit = (id?) => {
    if (id) this.props.history.push("/mall/item?id=" + id);
    else this.props.history.push("/mall/item");
  };

  sale = (id, isSale) => {
    this.props.dispatch({
      type: "item/itemSale",
      payload: {
        form: { id, isSale },
        callback: () => {
          this.getItems();
        }
      }
    });
  };

  remove = id => {
    this.props.dispatch({
      type: "item/removeItem",
      payload: {
        form: { id },
        callback: () => {
          message.success("已经删除该商品");
          this.getItems();
        }
      }
    });
  };

  setItemToPop = id => {
    this.props.dispatch({
      type: "item/setItemToPop",
      payload: {
        form: { id },
        callback: () => {
          message.success("已经置顶该商品");
          this.getItems();
        }
      }
    });
  };

  setItemToNotPop = id => {
    this.props.dispatch({
      type: "item/setItemToNotPop",
      payload: {
        form: { id },
        callback: () => {
          message.success("已经取消置顶该商品");
          this.getItems();
        }
      }
    });
  };

  storeChange = storeId => {
    this.props.item.storeId = storeId;
    this.getItemCategories({ storeId });
    this.getRecommendCategories({ storeId });
    this.getItems({ storeId });
  };

  render(): JSX.Element {
    const { getFieldDecorator } = this.props.form;
    const { loading } = this.props;
    const {
      storeId,
      items: { totalCount, items },
      itemCategories: { items: itemCategories },
      recommendCategories: { items: recommendCategories },
      stores: { items: stores },
      itemSearchs: {
        keywords,
        pageIndex,
        pageSize,
        itemCategoryId,
        recommendCategoryId,
        isHot,
        isSale,
        isGroup,
        isTimeLimit,
        isBargain,
        isReleasePoints
      }
    } = this.props.item;
    // const storeName = Enumerable.from(stores).where(x => x['id'] == storeId).select(x => x['name']).firstOrDefault() + '全部';
    const pageChange = (pageIndex, pageSize) => {
      let payload = Object.assign({}, this.props.item.itemSearchs, {
        pageIndex,
        pageSize
      });
      this.getItems(payload);
    };
    const pagination: PaginationProps | boolean = {
      total: totalCount,
      defaultCurrent: 1,
      current: pageIndex,
      pageSize: pageSize,
      showSizeChanger: true,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      pageSizeOptions: ["10", "20", "30", "50"],
      onShowSizeChange: pageChange,
      onChange: pageChange
    };
    return (
      <Row className={Styles.F_BG_WHITE1}>
        <Row className={Styles.F_BG_WHITE}>
          <Col span={24}>
            <Form layout="inline">
              <Form.Item label="请选择店铺">
                {getFieldDecorator("storeId", {
                  initialValue: storeId
                })(
                  <Select style={{ width: 120 }} onChange={this.storeChange}>
                    {stores.map((store: api.SingleUserMallStoresVOStoreVO) => {
                      return (
                        <Select.Option value={store.id}>
                          {store.name}
                        </Select.Option>
                      );
                    })}
                  </Select>
                )}
              </Form.Item>
              <Form.Item label="关键字搜索">
                {getFieldDecorator("keywords", {
                  initialValue: keywords
                })(<Input size={size} placeholder="请输入商品名称/标签" />)}
              </Form.Item>
              <Form.Item label="商品分类">
                {getFieldDecorator("itemCategoryId", {
                  initialValue: itemCategoryId
                })(
                  <Select style={{ width: 120 }}>
                    <Select.Option value="">全部</Select.Option>
                    {itemCategories.map(
                      (i: api.SingleUserMallItemsVOItemCategoryVO) => {
                        return i.subItemCategories &&
                          i.subItemCategories.length > 0 ? (
                          <Select.OptGroup key={i.id} label={i.name}>
                            <Select.Option value={i.id}>{i.name}</Select.Option>
                            {i.subItemCategories.map(subItem => {
                              return (
                                <Select.Option value={subItem.id}>
                                  {subItem.name}
                                </Select.Option>
                              );
                            })}
                          </Select.OptGroup>
                        ) : (
                          <Select.Option value={i.id}>{i.name}</Select.Option>
                        );
                      }
                    )}
                  </Select>
                )}
              </Form.Item>
              <Form.Item label="是否团购">
                {getFieldDecorator("isGroup", {
                  initialValue: isGroup
                })(
                  <Select style={{ width: 80 }}>
                    <Select.Option value={`true`}>是</Select.Option>
                    <Select.Option value={`false`}>否</Select.Option>
                  </Select>
                )}
              </Form.Item>
              {/* <Form.Item label="是否抢购">
                {getFieldDecorator("isTimeLimit", {
                  initialValue: isTimeLimit
                })(
                  <Select style={{ width: 80 }}>
                    <Select.Option value={`true`}>是</Select.Option>
                    <Select.Option value={`false`}>否</Select.Option>
                  </Select>
                )}
              </Form.Item> */}
              <Form.Item label="是否砍价">
                {getFieldDecorator("isBargain", {
                  initialValue: isBargain
                })(
                  <Select style={{ width: 80 }}>
                    <Select.Option value={`true`}>是</Select.Option>
                    <Select.Option value={`false`}>否</Select.Option>
                  </Select>
                )}
              </Form.Item>
              <Form.Item label="是否释放体验金">
                {getFieldDecorator("isReleasePoints", {
                  initialValue: isReleasePoints
                })(
                  <Select style={{ width: 80 }}>
                    <Select.Option value={`true`}>是</Select.Option>
                    <Select.Option value={`false`}>否</Select.Option>
                  </Select>
                )}
              </Form.Item>
              <Form.Item label="是否上架">
                {getFieldDecorator("isSale", {
                  initialValue: isSale
                })(
                  <Select style={{ width: 80 }}>
                    <Select.Option value="">全部</Select.Option>
                    <Select.Option value={`true`}>是</Select.Option>
                    <Select.Option value={`false`}>否</Select.Option>
                  </Select>
                )}
              </Form.Item>
              {storeId ? (
                <Form.Item>
                  <Button size={size} onClick={() => this.edit()}>
                    新增
                  </Button>
                </Form.Item>
              ) : null}
              {storeId ? (
                <Form.Item>
                  <Button
                    size={size}
                    type="primary"
                    loading={loading}
                    onClick={this.search}
                  >
                    查询
                  </Button>
                </Form.Item>
              ) : null}
            </Form>
            <Col span={24}>
              <hr className={Styles.hrBorder} />
              <h3>商品列表</h3>
            </Col>
            <Col span={24}>
              <Table
                dataSource={items}
                bordered
                pagination={pagination}
                rowKey={(record: api.SingleUserMallItemsVOItemVO) =>
                  String(record.id)
                }
                loading={loading}
              >
                <Table.Column
                  title="序号"
                  key="no"
                  render={(text, record, index) => {
                    return (pageIndex - 1) * pageSize + index + 1;
                  }}
                />
                <Table.Column title="商品Id" key="id" dataIndex="id" />
                <Table.Column title="名称" key="name" dataIndex="name" />
                <Table.Column
                  title="图片"
                  key="picture"
                  render={(
                    text,
                    record: api.SingleUserMallItemsVOItemVO,
                    index
                  ) => {
                    return <img width="100px" src={record.picture} />;
                  }}
                />
                <Table.Column
                  title="商品分类"
                  key="itemCategoryName"
                  dataIndex="itemCategoryName"
                />
                <Table.Column
                  title="推荐类型"
                  key="recommendCategoryTitle"
                  dataIndex="recommendCategoryTitle"
                />
                <Table.Column
                  title="月销量"
                  key="monthSale"
                  dataIndex="monthSale"
                />
                <Table.Column
                  title="总销量"
                  key="totalSale"
                  dataIndex="totalSale"
                />
                <Table.Column
                  title="是否上架"
                  key="isSale"
                  render={(
                    text,
                    record: api.SingleUserMallItemsVOItemVO,
                    index
                  ) => {
                    return record.isSale == true ? "是" : "否";
                  }}
                />
                {/* <Table.Column
                  title="是否抢购"
                  key="isTimeLimit"
                  render={(
                    text,
                    record: api.SingleUserMallItemsVOItemVO,
                    index
                  ) => {
                    return record.isTimeLimit == true ? "是" : "否";
                  }}
                /> */}
                <Table.Column
                  title="是否团购"
                  key="isGroup"
                  render={(
                    text,
                    record: api.SingleUserMallItemsVOItemVO,
                    index
                  ) => {
                    return record.isGroup == true ? "是" : "否";
                  }}
                />
                <Table.Column
                  title="是否释放体验金"
                  key="isReleasePoints"
                  render={(
                    text,
                    record: api.SingleUserMallItemsVOItemVO,
                    index
                  ) => {
                    return record.isReleasePoints == true ? "是" : "否";
                  }}
                />
                <Table.Column
                  title="操作"
                  render={(
                    text,
                    record: api.SingleUserMallItemsVOItemVO,
                    index
                  ) => {
                    return (
                      <div>
                        <a
                          className={Styles.M_RIGHT}
                          onClick={() => this.edit(record.id)}
                        >
                          编辑
                        </a>
                        {!record.isSale ? (
                          <a
                            className={Styles.M_RIGHT}
                            onClick={() => this.sale(record.id, true)}
                          >
                            上架
                          </a>
                        ) : (
                          <a
                            className={Styles.M_RIGHT}
                            onClick={() => this.sale(record.id, false)}
                          >
                            下架
                          </a>
                        )}
                        {record.isSale && !record.isPop ? (
                          <a
                            className={Styles.M_RIGHT}
                            onClick={() => this.setItemToPop(record.id)}
                          >
                            置顶
                          </a>
                        ) : (
                          ""
                        )}
                        {record.isSale && record.isPop ? (
                          <a
                            className={Styles.M_RIGHT}
                            onClick={() => this.setItemToNotPop(record.id)}
                          >
                            取消置顶
                          </a>
                        ) : (
                          ""
                        )}
                        {/* {index > 0 ? (
                                                <a className={Styles.M_RIGHT} onClick={() => this.moveUp(record.id)}>
                                                    上移
                                                </a>) : null}
                                            {index < items.length - 1 ? (
                                                <a className={Styles.M_RIGHT} onClick={() => this.moveDown(record.id)}>
                                                    下移
                                                </a>) : null} */}
                        {/* <Popconfirm title="确定删除吗?" onConfirm={() => { this.remove(record.id); }}>
                                                <a>删除</a>
                                            </Popconfirm> */}
                      </div>
                    );
                  }}
                />
              </Table>
            </Col>
          </Col>
        </Row>
      </Row>
    );
  }
}

export default connect(({ item, loading: { models: { item: loading } } }) => ({
  item,
  loading
}))(Form.create()(Items));
